package com.leo.action;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.leo.business.UserBusiness;
import com.leo.formbean.UserForm;
import com.leo.util.InnerObjectUtile;
import com.leo.util.JsonUtil;
import com.leo.util.RegexUtil;
import com.leo.vo.AccessTokenResult;
import com.leo.vo.Result;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

public class UserAction extends ActionSupport implements ModelDriven<UserForm> {
	@Resource
	UserBusiness userBusiness;
	private UserForm userForm = new UserForm();
	
	public void login() {
		Result result = null;
		//String s = ServletActionContext.getRequest().getParameter("useCookie");
		try {
			result = userBusiness.Login(userForm);
		} catch (Exception e) {
			//e.printStackTrace();
			result = Result.unknownError();
		} finally {
			JsonUtil.output(result);
		}
	}
	
	public void regist() {
		Result result = null;
		try {
			result = userBusiness.regist(userForm);
		} catch (Exception e) {
			//e.printStackTrace();
			result = Result.unknownError();
		} finally {
			JsonUtil.output(result);
		}
	}
	
	//获取开发者信息，显示在开发者个人页面上
	public String getInfo() {
		try {
			userBusiness.getInfo();
		} catch (Exception e) {
			Result result = Result.unknownError();
			JsonUtil.output(result);
		}
		return SUCCESS;
	}
	
	public void updateInfo(){
		RegexUtil rgx = new RegexUtil();
		String password = userForm.getPassword(),
				passwordComfirm = userForm.getPasswordComfirm(),
				appURL = userForm.getAppURL();
		Result rs = null;
		if(!passwordComfirm.equals(password)) {
			rs = Result.error("两次新密码不一致");
			JsonUtil.output(rs);
		}
		else if(!rgx.userPasswordLegal(password, 6, 20)) {
			rs = Result.error("要求密码为长度6至20的合法字符");
		}
		else if(!rgx.isHttpURL(appURL)) {
			rs = Result.error("appURL地址不合法");
		}
		else if(!password.equals(passwordComfirm) ){
			rs = Result.error("两次输入的新密码不一致");
		}
		if(rs != null){
			JsonUtil.output(rs);
			return;
		}
		//get real username
		userForm.setUsername(InnerObjectUtile.SESSION.getMap().get("username"));
		rs = userBusiness.updateInfo(userForm);
		JsonUtil.output(rs);
	}
	
	public String logout() {
		userBusiness.logout();
		return "logout";
	}
	
	public String test(){
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setHeader("Cache-Control", "no-cache");
		response.setStatus(HttpServletResponse.SC_NOT_FOUND);
		return "404";
	}

	@Override
	public UserForm getModel() {
		return userForm;
	}
	
	public void getAccessToken(){
		try {
		AccessTokenResult result = userBusiness.getAccessToken(userForm);
		JsonUtil.output(result);
		}catch (Exception e) {
			JsonUtil.output(AccessTokenResult.serverError);
		}
	}
}